<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/3/11 0011
 * Time: 下午 11:59
 */
namespace api\controllers;

use common\models\BaseModels;
use common\models\kaoguobao\Order;
use common\models\kaoguobao\BenefitUser;
use common\models\kaoguobao\ResultParams;
use common\services\config\Config;
use common\services\UserService;
use common\services\OrderService;
use common\services\WXpay\WeiXinPayService;
use common\services\WXpay\lib\PayNotifyCallBack;

class OrderController extends BaseController
{
    /**
     * 微信支付回调入口
     */
    public function actionNotify()
    {
        $notify = new PayNotifyCallBack();
        $notify->Handle(false);
    }

    /**
     * 微信支付
     * @return array
     */
    public function actionWechatPay()
    {
        $orderId  = trim($this->request->get('order_id'));
        $key      = trim($this->request->get('key','kgb'));
        if(empty($orderId)){
            return $this->errorResult(Config::$notOrderId);
        }
        $result   = OrderService::orderWechat($orderId);
        if(empty($result)){
            return $this->errorResult(Config::$notOrder);
        }
        $orderBody = Order::$keyName[$result['key']];
        $orderNum  = $result['order_num'];
        $amount    = $result['amount'];;
        $openId    = $result['open_id'];
        $WXService = new WeiXinPayService();
        $resultData = $WXService->getPay($orderBody, $orderNum, $amount, $openId);
        $info =  <<<HTML
	//调用微信JS api 支付
	function jsApiCall(){
		WeixinJSBridge.invoke(
			'getBrandWCPayRequest',
			{$resultData['jsApiParameters']},
			function(res){
			
				if(res.err_msg == "get_brand_wcpay_request:ok"){
				    window.location.href = 'http://web.funfind.cn/details/result/{$orderId}';
				}
			}
		);
	}
	function callpay(){
		if (typeof WeixinJSBridge == "undefined"){
		    if( document.addEventListener ){
		        document.addEventListener('WeixinJSBridgeReady', jsApiCall, false);
		    }else if (document.attachEvent){
		        document.attachEvent('WeixinJSBridgeReady', jsApiCall);
		        document.attachEvent('onWeixinJSBridgeReady', jsApiCall);
		    }
		}else{
		    jsApiCall();
		}
	}
//获取共享地址
	function editAddress()
	{
		WeixinJSBridge.invoke(
			'editAddress',
			{$resultData['editAddress']},
			function(res){
				
			}
		);
	}
	window.onload = function(){
		if (typeof WeixinJSBridge == "undefined"){
		    if( document.addEventListener ){
		        document.addEventListener('WeixinJSBridgeReady', editAddress, false);
		    }else if (document.attachEvent){
		        document.attachEvent('WeixinJSBridgeReady', editAsddress); 
		        document.attachEvent('onWeixinJSBridgeReady', editAddress);
		    }
		}else{
			editAddress();
		}
	};
HTML;
        echo $info;
    }

    /**
     * 取消订单
     * @return array
     */
    public function actionOrderCancel()
    {
        $orderId  = trim($this->request->post('order_id'));
        $key      = trim($this->request->post('key','kgb'));
        if(empty($orderId)){
            return $this->errorResult(Config::$notOrderId);
        }
        $result = OrderService::orderCancel($orderId);
        if($result == '3'){
            return $this->errorResult(Config::$ok);
        }elseif($result == '2'){
            return $this->errorResult(Config::$cancelFail);
        }elseif ($result == '1'){
            return $this->errorResult(Config::$notOrder);
        }else{
            return $this->errorResult(Config::$notOrderId);
        }
    }
    /**
     * 订单状态查看接口
     * @return array
     */
    public function actionOrderResult()
    {
        $orderId  = trim($this->request->post('order_id'));
        $key      = trim($this->request->post('key'));
        if(empty($orderId)){
            return $this->errorResult(Config::$notOrderId);
        }
        if(empty(Order::$key[$key])){
            return $this->errorResult(Config::$notKey);
        }
        $result = Order::findOne($orderId);
        if(empty($result)){
            return $this->errorResult(Config::$notOrder);
        }
        $info = [
            'value'     => '￥0.00',
            'product'   => Order::$keyName[$key],
        ];
        // 订单状态业务判断 不等于0就表示已付款
        if(isset($result->order_status)
            && ($result->order_status != Order::ORDER_STATUS_STAY_PAY
                || $result->order_status != Order::ORDER_STATUS_OVERTIME)){
            $info['value'] = '￥'. number_format($result->amount / 100, 2);
            return $this->endReponse('0',$info);
        }
        return $this->endReponse('101',$info);
    }
    /**
     * 订单列表页
     * @return array
     */
	public function actionUserOrderList()
    {
        $wechatId   = $this->user_id;
        if(!$wechatId){
            return $this->errorResult(Config::$notLogin);
        }
        $key     = trim($this->request->post('key'));
        $info    = [];
        if(empty(Order::$key[$key])){
            return $this->errorResult(Config::$notKey);
        }
        $userId = UserService::userData($wechatId);
        if($userId == false){
            return $this->errorResult(Config::$notUser);
        }
        $data = OrderService::orderUserDataQuery($userId,$key);
        if(empty($data)){
            return $this->endReponse('0',$info);
        }
        $info['title']   = Order::$keyName[$key];
        $info['content'] = $data;
        return $this->endReponse('0',$info);
    }

    /**
     * 订单详情页
     * @return array
     */
    public function actionQueryOrderDetails()
    {
        $wechatId   = $this->user_id;
        if(!$wechatId){
            return $this->errorResult(Config::$notLogin);
        }
        $OrderId  = trim($this->request->post('order_id'));
        $key     = trim($this->request->post('key'));
        if(empty($OrderId)){
            return $this->errorResult(Config::$notOrderId);
        }
        if(empty(Order::$key[$key])){
            return $this->errorResult(Config::$notKey);
        }
        $result = OrderService::onlyOrderList($OrderId,$key);
        if(empty($result)){
            return $this->errorResult(Config::$notOrder);
        }
        return $this->endReponse('0',$result);
    }

    /**
     * 理赔状态查询
     * @return array
     */
    public function actionOrderStatusResult()
    {
        $wechatId   = $this->user_id;
        if(!$wechatId){
            return $this->errorResult(Config::$notLogin);
        }
        $orderId  = trim($this->request->post('order_id'));
        $key      = trim($this->request->post('key'));
        if(empty($orderId)){
            return $this->errorResult(Config::$notOrderId);
        }
        if(empty(Order::$key[$key])){
            return $this->errorResult(Config::$notKey);
        }
        // 订单信息
        $orderData = Order::find()
            ->where(['id' => $orderId])
            ->andWhere(['key' => $key])
            ->limit(1)->asArray()->one();
        if(empty($orderData)){
            return $this->errorResult(Config::$notOrder);
        }
        // 查询受益人信息
        $user = BenefitUser::find()->where(['id' => $orderData['benefit_id']])->limit(1)->one();
        // 订单刚刚提交图片，待审核
        // 判断订单状态，赋予相对应的返回值type
        if($orderData['order_status'] == Order::ORDER_STATUS_UP_PROOF){
            $type = ResultParams::TYPE_NOTICE;                                  // 审核中
        }elseif($orderData['order_status'] == Order::ORDER_STATUS_HANDLED
                ||
                $orderData['order_status'] == Order::ORDER_STATUS_CLOSE){
            $type = ResultParams::TYPE_SUCCESS;                                 // 成功
        }else{
            $type = ResultParams::TYPE_ERROR;                                   // 其余的都是失败
        }
        $resultParams = ResultParams::find()
            ->where(['key' => $key])
            ->andWhere(['type' => $type])
            ->andWhere(['is_valid' => BaseModels::MODEL_IS_VALID])
            ->limit(1)->asArray()->one();
        $info = [
            'type'          => ResultParams::$type[$type],
            'headText'      => $resultParams['head_text']??'',
            'product'       => $resultParams['product']??'',
            'time'          => date('Y-m-d H:i:s',$orderData['updated_at']),
            'applicant'     => $user->benefit_user_name??'',
            'statusText'    => $resultParams['status_text']??'',
        ];
        return $this->endReponse('0',$info);
    }

    /**
     * 下单接口，数据入库请求
     * @return array
     */
    public function actionUserInformationSet()
    {
        $wechatId   = $this->user_id;
        if(!$wechatId){
            return $this->errorResult(Config::$notLogin);
        }
//        $wechatId = 10093;
        // 购买人信息
        $userName   = trim($this->request->post('user_name'));   // -姓名
        $phone      = trim($this->request->post('phone'));       // -手机号
        $mail       = trim($this->request->post('mail'));        // -邮箱
        $birthday   = trim($this->request->post('birthday'));    // -生日
        $sex        = trim($this->request->post('sex'));         // -性别

        $invite     = trim($this->request->post('invite'));      // -邀请人
        $cardType   = trim($this->request->post('card_type'));   // -卡类型  （选填）
        $cardNumber = trim($this->request->post('card_number')); // -身份证id  （选填）

        // 受益人资料
        $relation            = trim($this->request->post('relation'));              // -与购买人关系
        $benefitUserName     = trim($this->request->post('benefit_user_name'));     // -受益人资料
        $benefitUserSex      = trim($this->request->post('benefit_user_sex'));      // -受益人性别
        $benefitCardType     = trim($this->request->post('benefit_card_type'));     // -卡类型（非必填）
        $benefitUserNum      = trim($this->request->post('benefit_user_num'));      // -卡号码（非必填）
        $benefitUserPhone    = trim($this->request->post('benefit_user_phone'));    // -手机号
        $benefitUserMail     = trim($this->request->post('benefit_user_mail'));     // -邮箱
        $benefitUserProvince = trim($this->request->post('benefit_user_province')); // -省份
        $benefitUserCity     = trim($this->request->post('benefit_user_city'));     // -市
        $benefitUserArea     = trim($this->request->post('benefit_user_area'));     // -区
        $benefitUserSchool   = trim($this->request->post('benefit_user_school'));   // -学校（非必填）

        $orderType           = trim($this->request->post('order_type'));            // -保障项目
        $orderKey            = trim($this->request->post('key'));                   // -产品值

        if(empty($userName) || empty($phone) || empty($mail)){
            return $this->errorResult(Config::$notOrderUser);
        }

        if(empty($relation)
            ||
            empty($benefitUserName)
            ||
            empty($benefitUserPhone)
            ||
            empty($benefitUserMail)
            ||
            empty($benefitUserProvince)
            ||
            empty($benefitUserCity)
            ||
            empty($benefitUserArea)
        ){
            return $this->errorResult(Config::$notBenefit);
        }

        if(empty($orderKey)){
            return $this->errorResult(Config::$parameter);
        }
        // 将数据请求服务端处理业务
        $data = [
            'userName'              => $userName,
            'cardType'              => $cardType??'',
            'cardNumber'            => $cardNumber??'',
            'phone'                 => $phone,
            'mail'                  => $mail,
            'birthday'              => $birthday??'',
            'sex'                   => $sex??'',
            'invite'                => $invite??'',
            'wechatId'              => $wechatId,

            'relation'              => $relation,
            'benefitUserName'       => $benefitUserName,
            'benefitUserSex'        => $benefitUserSex??'',
            'benefitCardType'       => $benefitCardType??'',
            'benefitUserNum'        => $benefitUserNum??'',
            'benefitUserPhone'      => $benefitUserPhone,
            'benefitUserMail'       => $benefitUserMail,
            'benefitUserProvince'   => $benefitUserProvince,
            'benefitUserCity'       => $benefitUserCity,
            'benefitUserArea'       => $benefitUserArea,
            'benefitUserSchool'     => $benefitUserSchool??'',
            'orderType'             => $orderType,
            'orderKey'              => $orderKey,
        ];
        $result = OrderService::userDataCreation($data);
        if(!$result){
            return $this->errorResult(config::$notOrderFail);
        }
        if(!is_numeric($result)){
            return $result;
        }
        return $this->endReponse('0',['order_id' => $result]);
    }
}